package xps.and.uudaijia.userclient.view.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.mapapi.search.core.PoiInfo;
import com.hitomi.cslibrary.CrazyShadow;
import com.hitomi.cslibrary.base.CrazyShadowDirection;
import com.jude.utils.JUtils;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscriber;
import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.EventBusCommond.EventBusRequestReserveTime;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.StringCommond;
import xps.and.uudaijia.userclient.data.baen.DoubleBean;
import xps.and.uudaijia.userclient.data.baen.PinCheYGBean;
import xps.and.uudaijia.userclient.data.baen.VehicleBean;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.util.DateTimePickDialogUtil;
import xps.and.uudaijia.userclient.util.GlobalPositionInfo;
import xps.and.uudaijia.userclient.util.JingtouBack;
import xps.and.uudaijia.userclient.view.MainActivity;
import xps.and.uudaijia.userclient.view.activity.MapViewActivity;
import xps.and.uudaijia.userclient.view.activity.ObtainAddressActivty;
import xps.and.uudaijia.userclient.view.activity.YHJSYActivity;
import xps.and.uudaijia.userclient.view.base.Pickers;
import xps.and.uudaijia.userclient.view.custom.PickerScrollView;

public class PincheInfoPanelFragment extends Fragment {
    @BindView(R.id.tv_start)
    public TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.a)
    AutoLinearLayout a;
    @BindView(R.id.bt_publishOrder)
    Button btPublishOrder;
    @BindView(R.id.tv_call_Immediately)
    TextView tv_call_Immediately;
    @BindView(R.id.tv_call_Reserve)
    TextView tv_call_Reserve;
    @BindView(R.id.tv_reservation_time)
    TextView tv_reservation_time;
    @BindView(R.id.al_reservation_time)
    AutoLinearLayout al_reservation_time;
    Calendar calendar = Calendar.getInstance();//来自时间选择控件
    Unbinder unbinder;
    CrazyShadow useCarImmediatelyShadow;
    CrazyShadow useCarReserveShadow;
    String endLngStr = "";
    String endLatStr = "";
    public static int PincheInfoPanelFragment_ObtainStart = 2;
    public static int PincheInfoPanelFragment_ObtainEnd = 3;
    @BindView(R.id.CF_Layout)
    AutoLinearLayout CFLayout;
    @BindView(R.id.ENF_Layout)
    AutoLinearLayout ENFLayout;
    @BindView(R.id.RS_Text)
    TextView RSText;
    @BindView(R.id.PC_Layout)
    public AutoLinearLayout PCLayout;
    @BindView(R.id.tv_trival_cost)
    TextView tvTrivalCost;
    @BindView(R.id.beishu_Text)
    TextView beishuText;
    @BindView(R.id.bei_Text)
    TextView beiText;

    @BindView(R.id.YHJ_Text)
    public TextView YHJText;
    public String couponId = "0";
    @BindView(R.id.PD_Layout)
    public AutoLinearLayout PDLayout;
    private List<Pickers> list; // 滚动选择器数据
    private String[] id;
    private String[] name;
    PickerScrollView pickerscrlllview;
    public String startLng = "";
    public String startLat = "";
    public String endLng = "";
    public String endLat = "";
    String renshu = "1";
    String pingche = "2";
    JingtouBack call;
    String dat;
    String startTime;
    String beishu="1";
    String userid;
    String tvEndLoca = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pinche_info_panle, container, false);
        unbinder = ButterKnife.bind(this, view);
        initFunctionLable();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (PDLayout.getVisibility() == View.GONE) {
            getBuPingCHeYG();
        } else {
            getPingCHeYG();
        }
        beiText.setVisibility(View.GONE);
        initData();
        call = (JingtouBack) getActivity();
        userid = getArguments().getString("userid");
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == PincheInfoPanelFragment_ObtainStart) {
            PoiInfo poi = data.getParcelableExtra(ObtainAddressActivty.RESPONCE);
            tvStart.setText(poi.name);
            startLat = poi.location.latitude + "";
            startLng = poi.location.longitude + "";
            call.getShuzhiBack(poi.location.latitude, poi.location.longitude);
        } else if (requestCode == PincheInfoPanelFragment_ObtainEnd) {
            PoiInfo poi = data.getParcelableExtra(ObtainAddressActivty.RESPONCE);
            tvEnd.setText(poi.name);
            endLat = poi.location.latitude + "";
            endLng = poi.location.longitude + "";
        }
        if (PDLayout.getVisibility() == View.GONE) {
            getBuPingCHeYG();
        } else {
            getPingCHeYG();
        }
    }

    public void hide() {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.hide(this);
        fragmentTransaction.commit();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventMainThread(EventBusRequestReserveTime commond) {
        if (commond.getFrom().equals(EventBusRequestReserveTime.FROM_PINCHE)) {
            Log.e("PincheInfoPanelFragment", commond.getFrom());
        }
    }

    void initFunctionLable() {
        useCarImmediatelyShadow = new CrazyShadow.Builder()
                .setContext(getActivity())
                .setDirection(CrazyShadowDirection.ALL)
                .setShadowRadius(JUtils.dip2px(3))
                .setCorner(JUtils.dip2px(10))
                .setBackground(getResources().getColor(R.color.colorPrimary))
                .setImpl(CrazyShadow.IMPL_DRAW)
                .action(tv_call_Immediately);
        useCarImmediatelyShadow.show();

        useCarReserveShadow = new CrazyShadow.Builder()
                .setContext(getActivity())
                .setDirection(CrazyShadowDirection.ALL)
                .setShadowRadius(JUtils.dip2px(3))
                .setCorner(JUtils.dip2px(10))
                .setBackground(getResources().getColor(R.color.colorPrimary))
                .setImpl(CrazyShadow.IMPL_DRAW)
                .action(tv_call_Reserve);
        useCarReserveShadow.hide();

        tv_call_Reserve.setTextColor(getResources().getColor(R.color.black));
        tv_call_Immediately.setTextColor(getResources().getColor(R.color.white));
    }


    void resetCallTypeLable() {
        useCarReserveShadow.hide();
        useCarImmediatelyShadow.hide();
        tv_call_Immediately.setTextColor(getResources().getColor(R.color.black));
        tv_call_Reserve.setTextColor(getResources().getColor(R.color.black));
    }

    @OnClick({R.id.CF_Layout, R.id.PC_Layout, R.id.YHJ_Text, R.id.ENF_Layout, R.id.bt_publishOrder, R.id.tv_call_Immediately, R.id.tv_call_Reserve, R.id.al_reservation_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.CF_Layout:
                Intent intentObtainStart = new Intent(getActivity(), ObtainAddressActivty.class);
                startActivityForResult(intentObtainStart, PincheInfoPanelFragment_ObtainStart);
                break;
            case R.id.ENF_Layout:
                Intent intentObtainEnd = new Intent(getActivity(), ObtainAddressActivty.class);
                startActivityForResult(intentObtainEnd, PincheInfoPanelFragment_ObtainEnd);
                break;
            case R.id.PC_Layout:
                showCustomizeDialog();
                break;
            case R.id.bt_publishOrder:
                if (tvStart.getText().toString().equals("正在获取位置...")) {
                    JUtils.Toast("请重新选择起点位置");
                } else {
                    getDouble();
                }
                break;
            case R.id.tv_call_Reserve:
                resetCallTypeLable();
                useCarReserveShadow.show();
                tv_call_Reserve.setTextColor(getResources().getColor(R.color.white));
                EventBus.getDefault().post(StringCommond.ON_GLOBALLAYOUT_CHANGES);
                pingche = "1";
                if (PDLayout.getVisibility() == View.GONE) {
                    getBuPingCHeYG();
                } else {
                    getPingCHeYG();
                }
                break;
            case R.id.tv_call_Immediately:
                resetCallTypeLable();
                useCarImmediatelyShadow.show();
                tv_call_Immediately.setTextColor(getResources().getColor(R.color.white));
                EventBus.getDefault().post(StringCommond.ON_GLOBALLAYOUT_CHANGES);
                pingche = "2";
                if (PDLayout.getVisibility() == View.GONE) {
                    getBuPingCHeYG();
                } else {
                    getPingCHeYG();
                }
                break;
            case R.id.al_reservation_time:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        getActivity(), null, tv_reservation_time, new DateTimePickDialogUtil.OnPickerListener() {
                    @Override
                    public void onConfirm(Calendar calendar) {
                        PincheInfoPanelFragment.this.calendar = calendar;
                    }

                    @Override
                    public void onDismiss() {
                    }
                });
                dateTimePicKDialog.dateTimePicKDialog();
                break;
            case R.id.YHJ_Text:
                Intent YHJSYintent = new Intent(getActivity(), YHJSYActivity.class);
                startActivity(YHJSYintent);
                break;
        }
    }

    public void showCustomizeDialog() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(getActivity());
        final View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.wheel_view, null);
        pickerscrlllview = (PickerScrollView) dialogView.findViewById(R.id.picker_rel);
        list = new ArrayList<Pickers>();
        id = new String[]{"1", "2", "3", "4"};
        name = new String[]{"1", "2", "3", "4"};
        for (int i = 0; i < name.length; i++) {
            list.add(new Pickers(name[i], id[i]));
        }
        // 设置数据，默认选择第一条
        pickerscrlllview.setData(list);
        pickerscrlllview.setSelected(0);

        pickerscrlllview.setOnSelectListener(new PickerScrollView.onSelectListener() {
            @Override
            public void onSelect(Pickers pickers) {
                RSText.setText("拼车人数" + pickers.getShowConetnt() + "人");
                renshu = pickers.getShowId();
                getPingCHeYG();
            }
        });
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        dialog.dismiss();
                    }
                });
        customizeDialog.show();
    }

    /**
     * 初始化数据
     */
    private void initData() {

    }

    public void getPingCHeYG() {

        UserNetWorks.getPingCHeYG(startLng, startLat, endLng, endLat, pingche, renshu, new Subscriber<PinCheYGBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

            }

            @Override
            public void onNext(PinCheYGBean pinCheYGBean) {
                PinCheYGBean.ReturnBodyBean returnBodyBean = pinCheYGBean.getReturn_body();
                if (returnBodyBean.getIsFareIncrease().equals("1")) {
                    tvTrivalCost.setText(returnBodyBean.getPrice() + "元 X");
                    beishuText.setText("" + returnBodyBean.getFareIncreaseRate() + "");
                    beiText.setVisibility(View.VISIBLE);
                } else if (returnBodyBean.getIsFareIncrease().equals("0")) {
                    tvTrivalCost.setText(returnBodyBean.getPrice() + "元");
                    beiText.setVisibility(View.GONE);
                }
            }
        });
    }

    public void getBuPingCHeYG() {
        UserNetWorks.getBuPingCHeYG(startLng, startLat, endLng, endLat, pingche, renshu, new Subscriber<PinCheYGBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

            }

            @Override
            public void onNext(PinCheYGBean pinCheYGBean) {
                PinCheYGBean.ReturnBodyBean returnBodyBean = pinCheYGBean.getReturn_body();
                if (returnBodyBean.getIsFareIncrease().equals("1")) {
                    tvTrivalCost.setText(returnBodyBean.getPrice() + "元 X");
                    beishuText.setText("" + returnBodyBean.getFareIncreaseRate() + "");
                    beiText.setVisibility(View.VISIBLE);
                } else if (returnBodyBean.getIsFareIncrease().equals("0")) {
                    tvTrivalCost.setText(returnBodyBean.getPrice() + "元");
                    beiText.setVisibility(View.GONE);
                }
            }
        });
    }


    void getKuaiCheNo() {
        GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
        dat = tv_reservation_time.getText().toString();
        if (dat.equals("立即出发")) {//获取当前时间
            Date curDate = new Date(System.currentTimeMillis() + 1000);//当前时间的 一秒 后
            startTime = curDate.getTime() / 1000 + "";
        } else {
            startTime = calendar.getTime().getTime() / 1000 + "";//否则使用已选择的时间
        }
        if (startLng.equals("")) {
            startLng = globalPositionInfo.bdLocation.getLongitude() + "";
        }

        if (startLat.equals("")) {
            startLat = globalPositionInfo.bdLocation.getLatitude() + "";
        }
        if (!tvEnd.getText().toString().equals("您要去哪里?")) {
            endLngStr = endLng;
            endLatStr = endLat;
            tvEndLoca = tvEnd.getText().toString();
        }
        UserNetWorks.getKuaiChe(startTime, startLng, startLat, tvStart.getText().toString(), endLng, endLat, tvEndLoca, "2",renshu, couponId, beishu, new Subscriber<VehicleBean>() {
            @Override
            public void onStart() {
                super.onStart();
                ((MainActivity) getActivity()).showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
                ((MainActivity) getActivity()).dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ((MainActivity) getActivity()).dissmisDialog();
            }

            @Override
            public void onNext(VehicleBean vehicleBean) {
                if (vehicleBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                    Intent intent = new Intent(getContext(), MapViewActivity.class);
                    intent.putExtra("userId", userid);
                    intent.putExtra("orderId", vehicleBean.getReturn_body());
                    intent.putExtra("startLng", startLng);
                    intent.putExtra("startLat", startLat);
                    intent.putExtra("endLngStr", endLngStr);
                    intent.putExtra("endLatStr", endLatStr);
                    intent.putExtra("orderType", "2");
                    intent.putExtra("YesNo", "2");
                    startActivity(intent);
                    YHJText.setText("优惠劵");
                    couponId = "0";
                } else if (vehicleBean.getReturn_code().equals("FAIL")) {
                    if (!tvEnd.getText().toString().equals("您要去哪里?")) {
                        JUtils.Toast(vehicleBean.getReturn_msg());
                    } else {
                        JUtils.Toast("请输入终点");
                    }
                }
            }
        });
    }

    void getKuaiCheYes() {
        GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
        dat = tv_reservation_time.getText().toString();
        if (dat.equals("立即出发")) {//获取当前时间
            Date curDate = new Date(System.currentTimeMillis() + 1000);//当前时间的 一秒 后
            startTime = curDate.getTime() / 1000 + "";
        } else {
            startTime = calendar.getTime().getTime() / 1000 + "";//否则使用已选择的时间
        }
        if (startLng.equals("")) {
            startLng = globalPositionInfo.bdLocation.getLongitude() + "";
        }

        if (startLat.equals("")) {
            startLat = globalPositionInfo.bdLocation.getLatitude() + "";
        }
        if (!tvEnd.getText().toString().equals("您要去哪里?")) {
            endLngStr = endLng;
            endLatStr = endLat;
            tvEndLoca = tvEnd.getText().toString();
        }
        UserNetWorks.getKuaiCheYse(startTime, startLng, startLat, tvStart.getText().toString(), endLng, endLat, tvEndLoca, "1", renshu, couponId, beishu, new Subscriber<VehicleBean>() {
            @Override
            public void onStart() {
                super.onStart();
                ((MainActivity) getActivity()).showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
                ((MainActivity) getActivity()).dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ((MainActivity) getActivity()).dissmisDialog();
            }

            @Override
            public void onNext(VehicleBean vehicleBean) {
                if (vehicleBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                    Intent intent = new Intent(getContext(), MapViewActivity.class);
                    intent.putExtra("userId", userid);
                    intent.putExtra("orderId", vehicleBean.getReturn_body());
                    intent.putExtra("startLng", startLng);
                    intent.putExtra("startLat", startLat);
                    intent.putExtra("endLngStr", endLngStr);
                    intent.putExtra("endLatStr", endLatStr);
                    startActivity(intent);
                    YHJText.setText("优惠劵");
                    couponId = "0";
                } else if (vehicleBean.getReturn_code().equals("FAIL")) {
                    if (!tvEnd.getText().toString().equals("您要去哪里?")) {
                        JUtils.Toast(vehicleBean.getReturn_msg());
                    } else {
                        JUtils.Toast("请输入终点");
                    }
                }
            }
        });
    }

    void getDouble() {
        UserNetWorks.getDouble("", new Subscriber<DoubleBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

            }

            @Override
            public void onNext(DoubleBean doubleBean) {
                DoubleBean.ReturnBodyBean returnBodyBean = doubleBean.getReturn_body();
                if (returnBodyBean.getIsFareIncrease().equals("1")) {
                    beishu = returnBodyBean.getFareIncreaseRate() + "";
                    final AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(getContext());
                    normalDialog.setTitle("溢价提醒");
                    normalDialog.setMessage("临时调整价格" + returnBodyBean.getFareIncreaseRate() + "倍");
                    normalDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (pingche.equals("2")) {
                                        getKuaiCheNo();
                                    } else {
                                        getPingCHeYG();
                                    }
                                }
                            });
                    normalDialog.setNegativeButton("关闭",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //...To-do
                                    dialog.dismiss();
                                }
                            });
                    // 显示
                    normalDialog.show();
                } else if (returnBodyBean.getIsFareIncrease().equals("0")) {
                    if (pingche.equals("2")) {
                        getKuaiCheNo();
                    } else {
                        getKuaiCheYes();
                    }
                }
            }
        });
    }
}